/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * Author: zhaoshujin
 * Date: 2011-6-2 上午10:09:02
 */
package com.hash;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhaoshujin
 * 
 */
public class Md5Hashing {

	private static Logger logger = LoggerFactory.getLogger(Md5Hashing.class);

	/**
	 * 一致性哈希算法 （lib ketama - consistent hash）
	 * 
	 * @param key
	 * @return
	 */
	public static long md5HashingAlg(String key) {

		MessageDigest md5 = null;

		try {

			md5 = MessageDigest.getInstance("MD5");

		} catch (NoSuchAlgorithmException e) {
			logger.error("No md5 algorithm found...");
			throw new IllegalStateException("No md5 algorithm found...");

		}

		md5.reset();

		try {
			md5.update(key.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Unknown string :" + key, e);
		}

		byte[] bKey = md5.digest();

		long res = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16) | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF);

		return res;

	}

	public static void main(String[] args) {

		System.out.println(md5HashingAlg("10.0.2.211:11211"));
		System.out.println(md5HashingAlg("10.0.2.215:11212"));
		System.out.println(md5HashingAlg("10.0.2.133:11211"));
		System.out.println(md5HashingAlg("ccx"));

	}
}
